from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponse, HttpResponseForbidden
from django.utils.translation import gettext_lazy as _
from .models import User, UserRole
from .forms import CustomUserCreationForm, UserLoginForm, SuperAdminUserCreationForm, SuperAdminUserChangeForm
from projects.models import Project, ProjectMember, Webhook
from django.db.models import Q

@login_required
def dashboard(request):
    """用户仪表盘视图"""
    # 获取用户参与的所有项目
    user_projects = Project.objects.filter(
        Q(members__user=request.user) | Q(created_by=request.user)
    ).distinct().order_by('-updated_at')
    
    # 获取用户创建的项目
    user_created_projects = Project.objects.filter(created_by=request.user)
    
    # 获取所有项目的Webhook消息并合并
    all_webhook_messages = []
    for project in user_projects:
        # 为每条消息添加项目信息
        for message in project.webhook_messages:
            message['project'] = project
            all_webhook_messages.append(message)
    
    # 按时间戳降序排序（最新的在前）
    all_webhook_messages.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
    
    return render(request, 'accounts/dashboard.html', {
        'user_projects': user_projects,
        'user_created_projects': user_created_projects,
        'webhook_messages': all_webhook_messages
    })

def user_login(request):
    """用户登录视图"""
    if request.user.is_authenticated:
        return redirect('/')
        
    if request.method == 'POST':
        form = UserLoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                messages.success(request, _('登录成功！'))
                return redirect('/')
    else:
        form = UserLoginForm()
        
    return render(request, 'accounts/login.html', {'form': form})

def user_logout(request):
    """用户登出视图"""
    logout(request)
    messages.success(request, _('您已成功登出！'))
    return redirect('accounts:login')

def register(request):
    """用户注册视图 - 已禁用，仅供参考"""
    # 用户注册功能已禁用，只允许超级管理员通过平台创建用户
    return redirect('accounts:login')

@login_required
def dashboard_test(request):
    """用户仪表盘测试视图"""
    # 获取用户参与的所有项目
    user_projects = Project.objects.filter(
        Q(members__user=request.user) | Q(created_by=request.user)
    ).distinct().order_by('-updated_at')
    
    # 获取用户所有项目的Webhook信息
    user_project_ids = user_projects.values_list('id', flat=True)
    user_webhooks = Webhook.objects.filter(project_id__in=user_project_ids).order_by('-created_at')
    
    return render(request, 'accounts/dashboard_test.html', {
        'user_webhooks': user_webhooks
    })

@login_required
def dashboard_fixed(request):
    """修复版用户仪表盘视图"""
    # 获取用户参与的所有项目
    user_projects = Project.objects.filter(
        Q(members__user=request.user) | Q(created_by=request.user)
    ).distinct().order_by('-updated_at')
    
    # 获取用户创建的项目
    user_created_projects = Project.objects.filter(created_by=request.user)
    
    # 获取最近的项目（最近更新的5个）
    recent_projects = user_projects[:5]
    
    # 为每个项目添加用户角色信息
    for project in recent_projects:
        try:
            membership = ProjectMember.objects.get(project=project, user=request.user)
            project.user_role = membership.role
        except ProjectMember.DoesNotExist:
            # 如果不是通过ProjectMember关联的项目，那就是创建者
            project.user_role = 'admin'
    
    # 获取用户所有项目的Webhook信息
    user_project_ids = user_projects.values_list('id', flat=True)
    user_webhooks = Webhook.objects.filter(project_id__in=user_project_ids).order_by('-created_at')
    
    return render(request, 'accounts/dashboard_fixed.html', {
        'user_projects': user_projects,
        'user_created_projects': user_created_projects,
        'recent_projects': recent_projects,
        'user_webhooks': user_webhooks
    })

@login_required
def simple_dashboard(request):
    """简单版本的用户仪表盘视图"""
    # 获取用户参与的所有项目
    user_projects = Project.objects.filter(
        Q(members__user=request.user) | Q(created_by=request.user)
    ).distinct().order_by('-updated_at')
    
    # 获取用户创建的项目
    user_created_projects = Project.objects.filter(created_by=request.user)
    
    # 获取所有项目的Webhook消息并合并
    all_webhook_messages = []
    for project in user_projects:
        # 为每条消息添加项目信息
        for message in project.webhook_messages:
            message['project'] = project
            all_webhook_messages.append(message)
    
    # 按时间戳降序排序（最新的在前）
    all_webhook_messages.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
    
    return render(request, 'accounts/simple_dashboard.html', {
        'user_projects': user_projects,
        'user_created_projects': user_created_projects,
        'webhook_messages': all_webhook_messages
    })

@login_required
def simple_webhook_list(request):
    """简单的Webhook清单视图"""
    # 获取用户参与的所有项目
    user_projects = Project.objects.filter(
        Q(members__user=request.user) | Q(created_by=request.user)
    ).distinct().order_by('-updated_at')
    
    # 获取用户所有项目的Webhook信息
    user_project_ids = user_projects.values_list('id', flat=True)
    user_webhooks = Webhook.objects.filter(project_id__in=user_project_ids).order_by('-created_at')
    
    return render(request, 'accounts/simple_webhook_list.html', {
        'user_webhooks': user_webhooks
    })

@login_required
def standalone_dashboard(request):
    """独立版本的用户仪表盘视图"""
    # 获取用户参与的所有项目
    user_projects = Project.objects.filter(
        Q(members__user=request.user) | Q(created_by=request.user)
    ).distinct().order_by('-updated_at')
    
    # 获取用户创建的项目
    user_created_projects = Project.objects.filter(created_by=request.user)
    
    # 获取所有项目的Webhook消息并合并
    all_webhook_messages = []
    for project in user_projects:
        # 为每条消息添加项目信息
        for message in project.webhook_messages:
            message['project'] = project
            all_webhook_messages.append(message)
    
    # 按时间戳降序排序（最新的在前）
    all_webhook_messages.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
    
    return render(request, 'accounts/standalone_dashboard.html', {
        'user': request.user,
        'user_projects': user_projects,
        'user_created_projects': user_created_projects,
        'webhook_messages': all_webhook_messages
    })


def super_admin_required(function):
    """装饰器：确保用户是超级管理员"""
    def wrap(request, *args, **kwargs):
        if request.user.is_authenticated and request.user.is_super_admin():
            return function(request, *args, **kwargs)
        else:
            messages.error(request, _('您没有权限访问此页面'))
            return redirect('accounts:dashboard')
    wrap.__doc__ = function.__doc__
    wrap.__name__ = function.__name__
    return wrap


@login_required
def user_list(request):
    """用户列表视图 - 所有登录用户可查看"""
    users = User.objects.all().order_by('-role', 'username')
    # 传递用户是否为超级管理员的信息到模板
    is_super_admin = request.user.is_super_admin()
    return render(request, 'accounts/user_list.html', {
        'users': users,
        'is_super_admin': is_super_admin
    })


@login_required
@super_admin_required
def user_create(request):
    """创建用户视图 - 仅超级管理员可访问"""
    if request.method == 'POST':
        form = SuperAdminUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            messages.success(request, _('用户创建成功！'))
            return redirect('accounts:user_list')
    else:
        form = SuperAdminUserCreationForm()
    
    return render(request, 'accounts/user_form.html', {'form': form, 'title': _('创建用户')})


@login_required
@super_admin_required
def user_delete(request, user_id):
    """删除用户视图 - 仅超级管理员可访问"""
    user = get_object_or_404(User, id=user_id)
    
    # 防止超级管理员删除自己
    if user.id == request.user.id:
        messages.error(request, _('您不能删除自己的账号'))
        return redirect('accounts:user_list')
    
    if request.method == 'POST':
        username = user.username
        user.delete()
        messages.success(request, _('用户 %(username)s 已成功删除') % {'username': username})
        return redirect('accounts:user_list')
    
    return render(request, 'accounts/user_confirm_delete.html', {'user': user})


@login_required
def profile_edit(request):
    """用户编辑自己资料的视图"""
    user = request.user
    
    if request.method == 'POST':
        form = CustomUserChangeForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            messages.success(request, _('个人资料已成功更新！'))
            return redirect('accounts:dashboard')
    else:
        form = CustomUserChangeForm(instance=user)
    
    return render(request, 'accounts/user_form.html', {'form': form, 'title': _('编辑个人资料')})


@login_required
@super_admin_required
def user_edit(request, user_id):
    """超级管理员编辑用户的视图"""
    user = get_object_or_404(User, id=user_id)
    
    if request.method == 'POST':
        form = SuperAdminUserChangeForm(request.POST, instance=user)
        if form.is_valid():
            # 防止超级管理员撤销自己的超级管理员角色
            if user.id == request.user.id and form.cleaned_data['role'] != UserRole.SUPER_ADMIN:
                messages.error(request, _('您不能撤销自己的超级管理员角色'))
                return redirect('accounts:user_edit', user_id=user_id)
            
            form.save()
            messages.success(request, _('用户信息已成功更新！'))
            return redirect('accounts:user_list')
    else:
        form = SuperAdminUserChangeForm(instance=user)
    
    return render(request, 'accounts/user_form.html', {'form': form, 'title': _('编辑用户'), 'editing_user': user})
